<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>基础的get请求</title>
  <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
  <script src="https://cdn.bootcdn.net/ajax/libs/nprogress/0.2.0/nprogress.js"></script>
</head>

<body>
  <h1>POST请求</h1>
  <form id="form">
    <input type="text" name="name">
    <input type="text" name="age">
    <input type="text" name="sex">
    <button id="btn">提交</button>
  </form>
  <script>
    const oForm = document.getElementById('form')
    const oName = document.querySelector('#form input[name=name]');
    const oAge = document.querySelector('#form input[name=age]');
    const oSex = document.querySelector('#form input[name=sex]');
    const oBtn = document.getElementById('btn')
    oForm.onsubmit = function(){
      const nameValue = oName.value
      const ageValue = oAge.value
      const sexValue = oSex.value
      const xhr = new XMLHttpRequest()
      xhr.open('post','/adduser',true)
      // xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded;charset=utf-8')
      // xhr.send(`name=${nameValue}&age=${ageValue}&sex=${sexValue}`)
      xhr.setRequestHeader('Content-Type','application/json;charset=utf-8')
      xhr.send(JSON.stringify({
        name: nameValue,
        age: ageValue,
        sex: sexValue
      }))
      xhr.onreadystatechange = function(){
        if(xhr.readyState === 4 && xhr.status >= 200 && xhr.status <= 299){
          console.log(xhr.responseText);
        }
      }
      return false
    }




    // oForm.onsubmit = function () {
    //   //收集表单数据
    //   const nameValue = oName.value;
    //   const ageValue = oAge.value;
    //   const sexValue = oSex.value;

    //   const xhr = new XMLHttpRequest();

    //   xhr.open("POST", "/adduser", true);

    //   //请求体的数据放在send中传递
    //   //因为请求体类型有很多,所以发送请求的时候一定要设置请求头的Content-Type类型
    //   // xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
    //   // xhr.send(`name=${nameValue}&age=${ageValue}&sex=${sexValue}`);

    //   xhr.setRequestHeader("Content-Type", "application/json;charset=utf-8")
    //   xhr.send(JSON.stringify({
    //     name: nameValue,
    //     age: ageValue,
    //     sex: sexValue
    //   }));

    //   xhr.onreadystatechange = function () {
    //     if (xhr.readyState === 4 && (xhr.status >= 200 && xhr.status <= 299)) {
    //       console.log(xhr.responseText);
    //     }
    //   }
    //   return false
    // }
  </script>
</body>

</html>